package com.zlm.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页都可以访问，功能页只有有权限的人才可以访问
        http.authorizeRequests().antMatchers("/").permitAll()
                //add路径下VIP2角色可以访问
                .antMatchers("/add/**").hasAnyRole("vip2")
                .antMatchers("/update/**").hasRole("vip1");
        //防止网络攻击  disable为关闭
        http.csrf().disable();

        //设置登录页路劲
        http.formLogin().loginPage("/toLogin")
                //设置前端用户名密码字段
                .usernameParameter("username").passwordParameter("pwd")
                //设置登录请求路径
                .loginProcessingUrl("/login")
                //设置失败路径，可以获取异常数据
                .failureUrl("/login/error")
                //设置请求成功后请求的路径
                .successForwardUrl("/index")
                .and()
                //记住我功能
                .rememberMe().rememberMeParameter("remember")
                //有效时间
                .tokenValiditySeconds(60);

    }

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zlm").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2")
                .and()
                .withUser("zs").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");
    }
}
